from google.appengine.ext import db, blobstore
import datetime

def UserPathGen():
    return db.Key.from_path("User", "NonAdmin")

def OfferPathGen():
    return db.Key.from_path("Listings", "Offer")

def MessagePathGen():
    return db.Key.from_path("Communicate","Message")

class User(db.Model):
    user_id = db.StringProperty()
    email = db.EmailProperty()
    biopic = blobstore.BlobReferenceProperty()
    username = db.StringProperty()
    firstName = db.StringProperty()
    lastName = db.StringProperty()
    middleName = db.StringProperty(default='')
    nickname = db.StringProperty()
    bio = db.StringProperty()
    creds = db.IntegerProperty(default=5)
    reputation = db.IntegerProperty(default=0)
    publicReputation = db.IntegerProperty()
    language = db.StringProperty(default='EN')
    isAdmin = db.BooleanProperty(default=False)
    timeCreated = db.DateTimeProperty(auto_now_add=True)
    tutees = db.ListProperty(db.Key)

class TutorOffer(db.Model):
    tutor = db.ReferenceProperty(User)
    subject = db.CategoryProperty()
    description = db.TextProperty()
    price = db.IntegerProperty()
    timeCreated = db.DateTimeProperty(auto_now_add=True)
    isDone = db.BooleanProperty(default=False)
    title = db.StringProperty()
    tags = db.ListProperty(str)

class Communication(db.Model):
    message = db.TextProperty()
    subject = db.StringProperty()
    sender = db.ReferenceProperty(User)
    receivers = db.ListProperty(db.Key)
    item = db.ReferenceProperty(TutorOffer)

def TagPathGen(tag):
    return db.Key.from_path("Tags", tag)

class Tag(db.Model):
    tag = db.StringProperty()
    taggedOffers = db.ListProperty(db.Key)
    numOffers = db.IntegerProperty(default=1)

def processTags(tags, offer):
    '''Process a list of tags.'''
    alreadyWentThrough = set()
    for tag in tags:
        if tag == '':
            continue
        if tag in alreadyWentThrough:
            continue
        else:
            alreadyWentThrough.add(tag)
            newTag = Tag.all().ancestor(TagPathGen(tag)).get()
            if newTag:
                newTag.taggedOffers.append(offer.key())
                newTag.numOffers += 1
            else:
                newTag = Tag(parent=TagPathGen(tag), taggedOffers=[offer.key()],
                             tag=tag)
            newTag.put()

def LogPathGen():
    return db.Key.from_path("Logs", "LogsAgain")

class Log(db.Model):
    timeMade = db.DateTimeProperty(auto_now_add=True)
    message = db.StringProperty()
